(function () {
  var state = {
    page: 1,
    pageSize: 20,
    total: 0,
    loading: false,
  };

  var selectors = {
    orderNo: document.getElementById('filter-order-no'),
    sku: document.getElementById('filter-sku'),
    country: document.getElementById('filter-country'),
    status: document.getElementById('filter-status'),
    itemGroup: document.getElementById('filter-item-group'),
    stock: document.getElementById('filter-stock'),
    search: document.getElementById('orders-search'),
    reset: document.getElementById('orders-reset'),
    list: document.getElementById('orders-list'),
    empty: document.getElementById('orders-empty'),
    loading: document.getElementById('orders-loading'),
    pagination: document.getElementById('orders-pagination'),
    prev: document.getElementById('orders-prev'),
    next: document.getElementById('orders-next'),
    pageInfo: document.getElementById('orders-page-info'),
  };

  var STATUS_LABELS = {
    Draft: __('草稿'),
    'To Deliver': __('待出货'),
    'To Receive': __('待收货'),
    'To Bill': __('待开票'),
    Completed: __('已完成'),
    Closed: __('已关闭'),
    'On Hold': __('挂起'),
    Cancelled: __('已取消')
  };

  function __(text) {
    if (window.__ && typeof window.__ === 'function') {
      return window.__(text);
    }
    return text;
  }

  function getFilters() {
    return {
      order_no: (selectors.orderNo.value || '').trim(),
      sku: (selectors.sku.value || '').trim(),
      country: (selectors.country.value || '').trim(),
      status: selectors.status.value,
      item_group: (selectors.itemGroup.value || '').trim(),
      has_stock: selectors.stock.value,
    };
  }

  function setLoading(loading) {
    state.loading = loading;
    if (selectors.loading) {
      selectors.loading.hidden = !loading;
    }
  }

  function renderOrders(orders) {
    selectors.list.innerHTML = '';
    if (!orders || !orders.length) {
      selectors.empty.hidden = false;
      return;
    }

    selectors.empty.hidden = true;

    orders.forEach(function (order) {
      var card = document.createElement('div');
      card.className = 'order-card';

      var header = document.createElement('div');
      header.className = 'order-card-header';
      header.innerHTML = `
        <div class="order-meta">
          <div class="order-name">${__('订单号')}：${order.name || ''}</div>
          <div class="order-sub">${__('客户')}：${order.customer_name || '-'}</div>
        </div>
        <div class="order-status">
          <span class="status-chip">${STATUS_LABELS[order.status] || order.status || '-'}</span>
          <span class="status-sub">${__('日期')}：${order.transaction_date || '-'}</span>
        </div>`;
      card.appendChild(header);

      var info = document.createElement('div');
      info.className = 'order-card-info';
      info.innerHTML = `
        <div>${__('目的国')}：${order.country || '-'}</div>
        <div>${__('金额')}：${order.grand_total || 0} ${order.currency || ''}</div>
        <div>${__('库存情况')}：${order.has_stock ? __('有库存') : __('无库存')}</div>`;
      card.appendChild(info);

      var table = document.createElement('table');
      table.className = 'order-items-table';
      var thead = document.createElement('thead');
      thead.innerHTML = `
        <tr>
          <th>SKU</th>
          <th>${__('商品名称')}</th>
          <th>${__('物料组')}</th>
          <th>${__('数量')}</th>
          <th>${__('库存')}</th>
          <th>${__('仓库')}</th>
        </tr>`;
      table.appendChild(thead);

      var tbody = document.createElement('tbody');
      (order.items || []).forEach(function (item) {
        var tr = document.createElement('tr');
        var available = item.available_qty;
        if (typeof available === 'number') {
          available = available.toFixed(2);
        }
        tr.innerHTML = `
          <td>${item.item_code || '-'}</td>
          <td>${item.item_name || '-'}</td>
          <td>${item.item_group || '-'}</td>
          <td>${item.qty || 0} ${item.uom || ''}</td>
          <td>${available || 0}</td>
          <td>${item.warehouse || '-'}</td>`;
        tbody.appendChild(tr);
      });
      if (!tbody.children.length) {
        var tr = document.createElement('tr');
        tr.innerHTML = `<td colspan="6" class="order-empty-row">${__('该订单暂无商品')}</td>`;
        tbody.appendChild(tr);
      }
      table.appendChild(tbody);
      card.appendChild(table);

      selectors.list.appendChild(card);
    });
  }

  function updatePagination() {
    var totalPages = Math.ceil(state.total / state.pageSize) || 1;
    selectors.pagination.hidden = state.total <= state.pageSize;
    if (selectors.pageInfo) {
      selectors.pageInfo.textContent = __('第 {0}/{1} 页').replace('{0}', state.page).replace('{1}', totalPages);
    }
    selectors.prev.disabled = state.page <= 1;
    selectors.next.disabled = state.page >= totalPages;
  }

  function handleError(error) {
    console.error(error);
    frappe.msgprint ? frappe.msgprint({
      title: __('提示'),
      indicator: 'red',
      message: __('订单数据加载失败，请稍后重试。')
    }) : alert(__('订单数据加载失败。'));
  }

  function fetchOrders() {
    if (!selectors.list) {
      return;
    }

    setLoading(true);
    var params = getFilters();
    params.page = state.page;
    params.page_size = state.pageSize;

    var searchParams = new URLSearchParams();
    Object.keys(params).forEach(function (key) {
      if (params[key]) {
        searchParams.append(key, params[key]);
      }
    });

    fetch('/api/method/upsystem.upsystem.api.flowa_list_sales_orders?' + searchParams.toString(), {
      method: 'GET',
      headers: {
        'Accept': 'application/json'
      }
    })
      .then(function (res) { return res.json(); })
      .then(function (payload) {
        if (!payload || payload.exc) {
          throw new Error(payload ? payload.exc : 'API Error');
        }
        var message = payload.message || {};
        state.total = message.total || 0;
        renderOrders(message.data || []);
        updatePagination();
      })
      .catch(handleError)
      .finally(function () {
        setLoading(false);
      });
  }

  function resetFilters() {
    selectors.orderNo.value = '';
    selectors.sku.value = '';
    selectors.country.value = '';
    selectors.status.value = '';
    selectors.itemGroup.value = '';
    selectors.stock.value = '';
    state.page = 1;
    fetchOrders();
  }

  if (selectors.search) {
    selectors.search.addEventListener('click', function () {
      state.page = 1;
      fetchOrders();
    });
  }

  if (selectors.reset) {
    selectors.reset.addEventListener('click', function () {
      resetFilters();
    });
  }

  if (selectors.prev) {
    selectors.prev.addEventListener('click', function () {
      if (state.page > 1) {
        state.page -= 1;
        fetchOrders();
      }
    });
  }

  if (selectors.next) {
    selectors.next.addEventListener('click', function () {
      var totalPages = Math.ceil(state.total / state.pageSize) || 1;
      if (state.page < totalPages) {
        state.page += 1;
        fetchOrders();
      }
    });
  }

  if (selectors.orderNo) {
    selectors.orderNo.addEventListener('keyup', function (event) {
      if (event.key === 'Enter') {
        state.page = 1;
        fetchOrders();
      }
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function () {
      fetchOrders();
    });
  } else {
    fetchOrders();
  }
})();


